<template>
	<view class="profile-data">
		<scroll-view scroll-y="true"
					 class="scroll-Y">
			<view class="data-avatar">
				<u-image width="180rpx" height="180rpx" :src="profileForm.avatar" shape="circle" @click="chooseImage" :lazy-load="true"></u-image>
			</view>
			<view class="data-item">
				<u-form :model="profileForm" ref="profileForm">
					<u-form-item label="昵称" prop="nickname">
						<u-input v-model="profileForm.nickname" placeholder="请输入昵称" />
					</u-form-item>
					<u-form-item label="地区" prop="address">
						<u-input v-model="profileForm.address" placeholder="请选择" type="select" @click="setAddress" />
						<u-picker mode="region" v-model="addressShow" @confirm="addressConfirm"></u-picker>
					</u-form-item>
					<u-form-item label="简介" prop="sign" class="item-detail">
						<u-input style="border-radius: 20rpx;" :clearable="false" v-model="profileForm.sign" type="textarea" height="140" auto-height="true" placeholder="介绍自己的兴趣爱好～" />
						<!-- <textarea :value="" style="width: 660rpx;height: 140rpx;border-radius: 20rpx;padding: 10rpx 20rpx;background: #f2f2f2;font-size: 24rpx" placeholder="介绍自己的兴趣爱好～" /> -->
					</u-form-item>
					<u-form-item label="Uid" prop="Uid">
						<u-input v-model="uid" placeholder="请输入昵称" disabled />
					</u-form-item>
					<u-form-item label="性别" prop="sex">
						<u-input v-model="profileForm.sex" placeholder="请选择" type="select" @click="setSexShow" />
						<u-select v-model="sexShow" mode="single-column" :list="sexList" @confirm="sexConfirm"></u-select>
					</u-form-item>
					<u-form-item label="生日" prop="born">
						<u-input v-model="profileForm.born" placeholder="请选择" type="select" @click="setBornShow" />
<!--						<u-calendar v-model="bornShow" mode="date" @change="bornChange"></u-calendar>-->
						<u-picker v-model="bornShow" mode="time" :params="params" @confirm="bornChange"></u-picker>
					</u-form-item>
				</u-form>
			</view>
		</scroll-view>
		<view class="data-operation" v-if="!addressShow && !sexShow && !bornShow">
			<view class="operation-btn" @click="saveClick()">保存</view>
		</view>
	</view>
</template>

<script>
	import restApi from "../../../../lib/restapi";
	import IMService from "../../../../lib/imservice";
	import common from '../../../../utils/common.js'
	export default {
		data () {
			return {
				params: {
					year: true,
					month: true,
					day: true,
				},
				onButton: true,
				addressShow: false,
				sexShow: false,
				sexList: [
					{
						value: 0,
						label: '女'
					},
					{
						value: 1,
						label: '男'
					},
					{
						value: -1,
						label: '未知'
					}
				],
				bornShow: false,
				profileForm: {},
				rules: {
					nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
					address: [{ required: true, message: '请选择地区', trigger: 'change' }],
					sign: [
						{ required: true, message: '请输入简介', trigger: 'blur' },
						{ min: 5, message: '简介不能少于5个字', trigger: 'blur' }
					],
					sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
					born: [{ required: true, message: '请选择生日', trigger: 'change' }],
				}
			}
		},
		methods: {
			setBornShow(){
				this.bornShow = true
				uni.hideKeyboard();
			},
			setSexShow(){
				this.sexShow = true
				uni.hideKeyboard();
			},
			setAddress(){
				this.addressShow = true
				uni.hideKeyboard();
			},
			// 地区选择
			addressConfirm (object) {
				let address = []
				console.log(object)
				address.push(object.province.label, object.city.label, object.area.label)
				this.profileForm.address = address.join(',')
			},
			// 性别选择
			sexConfirm (e) {
				console.log(e)
				this.profileForm.sex = e[0].label
			},
			// 生日选择
			bornChange (e) {
				this.profileForm.born = e.year+'-'+e.month+'-'+e.day
			},
			// 更新信息
			saveClick () {
				let self = this
				let flag = common.checkRules(self.profileForm, self.rules)
				// 自定义表单验证，如果flag为true时表单验证通过,反之为false
				if (flag) {
					let sex = ''
					if (self.profileForm.sex === '女') {
						sex = 0
					} else if (self.profileForm.sex === '男') {
						sex = 1
					} else {
						sex = -1
					}
					self.$request(self.commonApi.updateUserInfo, 'POST', {
						address: self.profileForm.address,
						avatar: self.profileForm.avatar,
						born: self.profileForm.born,
						nickname: self.profileForm.nickname,
						sex: sex,
						sign: self.profileForm.sign
					}, 'application/json').then(res => {
						uni.showToast({
							title: '保存成功',
							duration: 1500,
							icon: 'none'
						})
						self.logout()
						setTimeout(()=>{
							uni.navigateBack({
								delta: 1
							})
						},500)
					})
				}
			},
			findUser(username, password) {
				let data = uni.getStorageSync('masterList')
				let dataList = JSON.parse(data)
				let reData = {}
				dataList.forEach(item=>{
					if(item.name == username && item.password == password){
						reData = {
							uuid: item.uuid,
							avatar: item.avatar,
							name: item.name
						}
					}
				})
				return reData
			},
			getUserData(){
				let name = uni.getStorageSync('userData')
				let user = this.findUser(name.nickname, '123');     //模拟登录
				if(user){
					uni.setStorageSync('currentUser', user);
				}
				let currentUser = uni.getStorageSync('currentUser');
				if(this.goEasy.getConnectionStatus() === 'disconnected') {
					getApp().globalData.imService= new IMService(this.goEasy,this.GoEasy);
					getApp().globalData.imService.connect(currentUser);
				}
				uni.showLoading();
				//监听会话列表变化
				let self = this;
				this.goEasy.im.on(this.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, (content) => {
					self.renderConversations(content);
				});
				//加载会话列表
				this.goEasy.im.latestConversations({
					onSuccess: function (result) {
						let content = result.content;
						self.renderConversations(content);
						uni.hideLoading();
					},
					onFailed: function (error) {
						//获取失败
						uni.hideLoading()
						console.log("失败获取最新会话列表, code:" + error.code + " content:" + error.content);
					}
				});
			},
			logout () {
			    this.goEasy.disconnect({
					onSuccess: function(){
						this.getUserData()
						console.log("GoEasy disconnect successfully.")
					},
					onFailed: function(error){
						console.log("Failed to disconnect GoEasy, code:"+error.code+ ",error:"+error.content);
					}
				});
			},
			// 头像上传
			chooseImage(){
				uni.chooseImage({
					count:1,
				    success: (chooseImageRes) => {
						// this.profileForm.avatar = chooseImageRes.tempFilePaths[0]
				        const tempFilePaths = chooseImageRes.tempFilePaths;
				        uni.uploadFile({
				        	url: this.commonApi.petAvatar,
				        	filePath: tempFilePaths[0],
				        	header: {
				        		token: uni.getStorageSync('token')
				        	},
				        	name: 'file',
				        	formData: {
				        		fileName: tempFilePaths[0]
				        	},
				        	success: res => {
								console.log(res)
				        		let img = JSON.parse(res.data);
				        		this.profileForm.avatar = img.data;
				        	},
				        	fail: res => {
				        	}
				        });
				    }
				});
			},
			// 获取用户基本信息
			getUserInfo () {
				const uid = uni.getStorageSync('uid')
				this.$request(this.commonApi.userInfo + uid, 'GET').then(res => {
					let items = res.data.data
					if (items.sex === 0) {
						items.sex = '女'
					} else if (items.sex === 1) {
						items.sex = '男'
					} else {
						items.sex = '未知'
					}
					this.profileForm = items
					this.profileForm.born = this.profileForm.born.slice(0,10)
				})
			}
		},
		mounted () {
			this.getUserInfo()
		},
		computed: {
			// 获取用户uid
			uid () {
				const uid = uni.getStorageSync('uid')
				return uid
			}
		}
	}
</script>

<style lang="scss" scoped>
	.profile-data {
		height: 100vh;
		position: relative;
		z-index: 2;
		.scroll-Y {
			height: calc(100vh - 170rpx);
		}
		.data-avatar {
			padding: 60rpx 284rpx;
			border-top: 2rpx solid #EDEDED;
		}
		.data-item {
			padding: 0 30rpx;
			/deep/ .u-form-item {
				padding: 10rpx 0!important;
			}
			/deep/ .u-input__input {
				text-align: right!important;
			}
			/deep/ .uicon-arrow-down-fill::before {
				content: "\e605"!important;
			}
			.item-detail {
				/deep/ .u-form-item__body {
					flex-direction: column!important;
				}
				/deep/ .u-input__input {
					text-align: left!important;
					width: 630rpx!important;
					background: #F9F9F9!important;
					border-radius: 12rpx!important;
					padding: 30rpx!important;
				}
				/deep/ .u-border-bottom::after {
					border-bottom-width: 0!important;
				}
			}
		}
		.data-operation {
			padding: 30rpx 30rpx 60rpx 30rpx;
			position: absolute;
			bottom: 0;
			left: 0;
			/*z-index: 1;*/
			.operation-btn {
				width: 690rpx;
				height: 80rpx;
				background: #F6F6F6;
				border-radius: 12rpx;
				text-align: center;
				font-size: 32rpx;
				font-weight: 500;
				color: #333333;
				line-height: 80rpx;
				z-index: 1;

			}
		}
	}
</style>
